<template>
  <div class="meeting-form-container">
    <el-form ref="formRef" label-width="120px" :model="formData" :rules="rules">
      <div class="form-section">
        <div class="section-title">基本信息</div>
        <el-form-item label="会议名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入会议名称" />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="会议类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择会议类型" style="width: 100%">
                <el-option label="人大会议" value="1" />
                <el-option label="政协会议" value="2" />
                <el-option label="普通会议" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否报名" prop="signUpType">
              <el-switch v-model="formData.signUpType" active-value="2" inactive-value="1" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 时间选择部分 -->
      <div class="form-section">
        <div class="section-title">时间设置</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="formData.startTime"
                :disabled-date="disablePastDates"
                format="YYYY-MM-DD HH:mm"
                placeholder="选择开始时间"
                style="width: 100%"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                @change="validateTimeRange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="formData.endTime"
                :disabled-date="disablePastDates"
                format="YYYY-MM-DD HH:mm"
                placeholder="选择结束时间"
                style="width: 100%"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                @change="validateTimeRange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="timeError" class="time-error-message">
          <el-alert :closable="false" show-icon type="warning">{{ timeError }}</el-alert>
        </div>
      </div>
      <!-- 会议室选择部分 -->
      <div class="form-section">
        <div class="section-title">会议室选择</div>

        <div v-if="!formData.startTime || !formData.endTime" class="room-tip">
          <el-alert :closable="false" description="请先选择会议时间，系统将为您推荐可用的会议室" show-icon type="info">
            <template #title>
              <strong>请选择会议时间</strong>
            </template>
          </el-alert>
        </div>

        <template v-else>
          <el-form-item label="会议室" prop="conferenceRoomId">
            <!-- 使用新的会议室选择组件 -->
            <room-selector
              v-model="formData.conferenceRoomId"
              :end-time="formData.endTime"
              :start-time="formData.startTime"
              @room-selected="onRoomSelected"
            />
          </el-form-item>

          <!-- 选中的会议室详情显示在RoomSelector组件内部 -->
        </template>
      </div>
      <!-- 附加信息部分 -->
      <div class="form-section">
        <div class="section-title">附加信息</div>
        <el-form-item label="主持人" prop="compere">
          <el-input v-model="formData.compere" placeholder="请输入主持人姓名" />
        </el-form-item>
        <!-- 
        <el-form-item label="是否需要签到" prop="isCheck">
          <el-switch v-model="formData.isCheck" />
        </el-form-item> -->

        <el-form-item label="是否开放会议" prop="isOpen">
          <el-switch v-model="formData.isOpen" />
          <span class="form-tip">关闭后会议将不对外开放</span>
        </el-form-item>
        <el-form-item label="住宿场所" prop="hotelManagementId">
          <el-select v-model="formData.hotelManagementId" clearable filterable :loading="hotelLoading" placeholder="请选择住宿场所">
            <el-option v-for="hotel in hotelList" :key="hotel.id" :label="hotel.name" :value="hotel.id" />
          </el-select>
          <span class="form-tip">若选择住宿场所，参会用户需要住宿签到</span>
        </el-form-item>
        <el-form-item label="会议描述" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入会议描述" :rows="3" type="textarea" />
        </el-form-item>
      </div>
      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button :loading="submitting" type="primary" @click="handleSubmit">提 交</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, watch } from 'vue'
import { getAllConferenceRooms } from '~/src/api/conferenceRoom'
import RoomSelector from './RoomSelector.vue'
import request from '/@/utils/request'

// 定义会议室类型接口
interface ConferenceRoom {
  id: string | number
  roomName: string
  capacity?: string | number
  positionDescription?: string
  area?: string | number
  equipment?: string
  [key: string]: any
}

const props = defineProps({
  isEdit: {
    type: Boolean,
    default: false,
  },
  initialData: {
    type: Object,
    default: () => ({}),
  },
})

const emit = defineEmits(['cancel', 'submit'])

// 表单数据
const formData = reactive({
  id: '',
  title: '',
  type: '3', // 默认普通会议
  startTime: '',
  endTime: '',
  conferenceRoomId: '',
  compere: '',
  remark: '',
  isCheck: false,
  status: true,
  isOpen: true,
  seatedImg: '',
  signUpType: '1',
  hotelManagementId: null,
})

// 表单引用
const formRef = ref<any>(null)
const timeError = ref('')
const submitting = ref(false)
const selectedRoom = ref<ConferenceRoom | null>(null)

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入会议名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  type: [{ required: true, message: '请选择会议类型', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  conferenceRoomId: [{ required: true, message: '请选择会议室', trigger: 'change' }],
  hotelManagementId: [],
}

// 酒店列表相关
const hotelList = ref<any[]>([])
const hotelLoading = ref(false)
const fetchHotelList = async () => {
  hotelLoading.value = true
  try {
    const res = await request.get('/api/hotelManagement', { params: { page: 1, limit: 100 } })
    if (res && res.code === 0 && res.result && Array.isArray(res.result.rows)) {
      hotelList.value = res.result.rows
    } else {
      hotelList.value = []
    }
  } catch {
    hotelList.value = []
  } finally {
    hotelLoading.value = false
  }
}

// 初始化数据
onMounted(() => {
  if (props.isEdit && props.initialData) {
    Object.keys(props.initialData).forEach((key) => {
      if (key in formData) {
        formData[key] = props.initialData[key]
      }
    })

    // 如果是编辑模式，直接获取选中的会议室详情
    if (formData.conferenceRoomId) {
      fetchSelectedRoomDetail(formData.conferenceRoomId)
    }
  }
  fetchHotelList()
})

// 禁用过去的日期
const disablePastDates = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 不允许选择昨天及以前的日期
}

// 监听时间变化
watch(
  [() => formData.startTime, () => formData.endTime],
  async ([newStartTime, newEndTime], [oldStartTime, oldEndTime]) => {
    // 只有当值真正变化时才处理
    if (newStartTime === oldStartTime && newEndTime === oldEndTime) return

    timeError.value = ''

    // 清空会议室选择
    if (!newStartTime || !newEndTime) {
      formData.conferenceRoomId = ''
      selectedRoom.value = null
      return
    }

    // 验证时间范围
    validateTimeRange()
  },
  { deep: true }
)

// 验证时间范围
const validateTimeRange = () => {
  const { startTime, endTime } = formData
  if (!startTime || !endTime) return true

  const start = new Date(startTime)
  const end = new Date(endTime)

  if (start >= end) {
    timeError.value = '结束时间必须晚于开始时间'
    return false
  }

  // // 检查是否跨天（可选，根据业务需要）
  // const startDay = dayjs(startTime).format('YYYY-MM-DD')
  // const endDay = dayjs(endTime).format('YYYY-MM-DD')

  // if (startDay !== endDay) {
  //   timeError.value = '会议时间不能跨天，请在同一天内选择'
  //   return false
  // }

  // 检查会议时长是否过长（可选，例如超过8小时）
  // const duration = dayjs(endTime).diff(dayjs(startTime), 'hour')
  // if (duration > 8) {
  //   timeError.value = '会议时长不能超过8小时'
  //   return false
  // }

  timeError.value = ''
  return true
}

// 处理会议室选择变化
const onRoomSelected = (room: ConferenceRoom | null = null) => {
  if (!formData.conferenceRoomId) {
    selectedRoom.value = null
    return
  }

  selectedRoom.value = room
}

// 格式化设备显示
const formatEquipment = (equipment) => {
  if (!equipment) return '无'

  // 如果是字符串，尝试分割
  if (typeof equipment === 'string') {
    return equipment.split(',').join('、')
  }

  // 如果是数组
  if (Array.isArray(equipment)) {
    return equipment.join('、')
  }

  return equipment
}

// 获取选中的会议室详情
const fetchSelectedRoomDetail = async (roomId: string | number) => {
  try {
    const res = await getAllConferenceRooms()
    const response = res as any

    if (response && response.code === 0 && response.result) {
      const roomList = response.result.rows || []
      const room = roomList.find((r) => r.id === roomId)
      if (room) {
        selectedRoom.value = room
      }
    }
  } catch (error) {
    console.error('获取会议室详情出错:', error)
  }
}

// 取消按钮处理
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消编辑吗？已填写的内容将不会保存', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      emit('cancel')
    })
    .catch(() => {
      // 用户取消操作，不做任何处理
    })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  if (typeof formRef.value.validate === 'function') {
    formRef.value.validate((valid: boolean) => {
      if (!valid) {
        ElMessage.error('表单验证失败，请检查输入')
        return
      }

      // 再次验证时间
      if (!validateTimeRange()) return

      submitting.value = true

      try {
        // 构建提交数据
        const submitData = { ...formData }

        // 确保编辑模式下有id字段
        if (props.isEdit && !submitData.id && props.initialData.id) {
          submitData.id = props.initialData.id
        }

        // 发送给父组件处理
        emit('submit', submitData)
      } catch (error) {
        console.error('表单提交出错:', error)
        ElMessage.error('提交失败，请重试')
      } finally {
        submitting.value = false
      }
    })
  } else {
    // 如果没有validate方法，进行简单验证
    if (!formData.title || !formData.type || !formData.startTime || !formData.endTime || !formData.conferenceRoomId) {
      ElMessage.error('请填写必要的会议信息')
      return
    }

    if (!validateTimeRange()) return

    submitting.value = true
    try {
      emit('submit', { ...formData })
    } catch (error) {
      console.error('表单提交出错:', error)
      ElMessage.error('提交失败，请重试')
    } finally {
      submitting.value = false
    }
  }
}
</script>

<style scoped>
.meeting-form-container {
  max-width: 800px;
  margin: 0 auto;
}

.form-section {
  padding: 20px;
  margin-bottom: 20px;
  background: #f8fbff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.section-title {
  padding-bottom: 10px;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
  border-bottom: 1px solid #eee;
}

.time-error-message {
  margin-top: 10px;
}

.loading-rooms {
  padding: 20px 0;
}

.room-tip {
  padding: 20px 0;
}

.no-rooms {
  padding: 20px 0;
}

.room-option {
  display: flex;
  flex-direction: column;
}

.room-name {
  font-weight: 600;
}

.room-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.selected-room-info {
  padding: 15px;
  margin-top: 15px;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.info-title {
  margin-bottom: 10px;
  font-weight: 600;
  color: #333;
}

.info-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.info-item {
  display: flex;
  margin-bottom: 8px;
}

.info-item .label {
  min-width: 50px;
  margin-right: 5px;
  color: #909399;
}

.form-actions {
  display: flex;
  gap: 20px;
  justify-content: center;
  margin-top: 30px;
}

.form-tip {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .info-content {
    grid-template-columns: 1fr;
  }
}
</style>
